/**
 * 统一的API服务层
 * 将项目中所有的API调用集中管理
 */

// @ts-ignore
import TurndownService from "turndown";
import i18n from "../locales/i18n";
import { t } from "i18next";
import MarkdownIt from "markdown-it";

// 环境变量配置
const FLOWISE_BASE_URL = process.env.REACT_APP_FLOWISE_BASE_URL || "http://localhost:3000";
const FLOWISE_API_KEY = process.env.REACT_APP_FLOWISE_API_KEY || "";
const CONTENT_API_BASE_URL = process.env.REACT_APP_CONTENT_API_BASE_URL || "http://localhost:7800";
const AI_MODEL_BASE_URL = process.env.REACT_APP_AI_MODEL_BASE_URL || "http://localhost:11434";
const FLIGHT_SEARCH_BASE_URL = process.env.REACT_APP_FLIGHT_SEARCH_BASE_URL || "http://localhost:7800";
const TRANSLATE_API_BASE_URL = process.env.REACT_APP_CONTENT_API_BASE_URL || "http://192.168.0.13:7800";

// Flow IDs
const CHAT_FLOW_ID = process.env.REACT_APP_CHAT_FLOW_ID || "";
const SUMMARY_FLOW_ID = process.env.REACT_APP_SUMMARY_FLOW_ID || "";
const TIME_PROCESSING_FLOW_ID = process.env.REACT_APP_TIME_PROCESSING_FLOW_ID || "";
const CONSTANTS_FLOW_ID = process.env.REACT_APP_CONSTANTS_FLOW_ID || "";
const THINKING_CHAIN_CHAT_ID = process.env.REACT_APP_THINKING_CHAIN_CHAT_ID || "";

// 统一的html-to-markdown实例配置
const turndownService = new TurndownService({
  headingStyle: "atx",
  hr: "---",
  bulletListMarker: "-",
  codeBlockStyle: "fenced",
  emDelimiter: "*",
  strongDelimiter: "**",
  linkStyle: "inlined",
  linkReferenceStyle: "full",
});

// API配置类型
export interface ApiConfig {
  baseUrl: string;
  apiKey?: string;
  timeout?: number;
}

// 聊天相关API配置
export const CHAT_API_CONFIG = {
  FLOW_ID: CHAT_FLOW_ID, // 使用环境变量
  BASE_URL: `${FLOWISE_BASE_URL}/api/v1/prediction`,
  ABORT_URL: `${FLOWISE_BASE_URL}/api/v1/chatmessage/abort`,
  API_KEY: FLOWISE_API_KEY,
};

// AI模型API配置
export const AI_MODEL_CONFIG = {
  BASE_URL: `${AI_MODEL_BASE_URL}/api/generate`,
  MODEL: "mistral:7b",
};

// 内容管理API配置
export const CONTENT_API_CONFIG = {
  BASE_URL: `${CONTENT_API_BASE_URL}/apis/ctrip/products`,
};

// 思维链API配置
export const THINKING_CHAIN_CONFIG = {
  BASE_URL: `${FLOWISE_BASE_URL}/api/v1/prediction`,
  CHAT_ID: THINKING_CHAIN_CHAT_ID,
};

// 总结API配置
export const SUMMARY_API_CONFIG = {
  FLOW_ID: SUMMARY_FLOW_ID,
  BASE_URL: `${FLOWISE_BASE_URL}/api/v1/prediction`,
  API_KEY: FLOWISE_API_KEY,
};

// 航班搜索API配置
export const FLIGHT_SEARCH_CONFIG = {
  BASE_URL: `${FLIGHT_SEARCH_BASE_URL}/apis/flights/search/roundtrip`,
};

// 时间处理API配置
export const TIME_PROCESSING_CONFIG = {
  FLOW_ID: TIME_PROCESSING_FLOW_ID,
  BASE_URL: `${FLOWISE_BASE_URL}/api/v1/prediction`,
  API_KEY: FLOWISE_API_KEY,
};

// 翻译API配置
export const TRANSLATE_API_CONFIG = {
  BASE_URL: `${TRANSLATE_API_BASE_URL}/data-translate/baidu-translate/translate`,
};

// 通用请求配置
interface RequestConfig {
  method?: "GET" | "POST" | "PUT" | "DELETE";
  headers?: Record<string, string>;
  body?: any;
  signal?: AbortSignal;
}

// 通用请求函数
async function request<T = any>(
  url: string,
  config: RequestConfig = {},
): Promise<T> {
  const { method = "GET", headers = {}, body, signal } = config;

  const fetchConfig: RequestInit = {
    method,
    headers: {
      "Content-Type": "application/json",
      ...headers,
    },
    signal,
  };

  if (body) {
    fetchConfig.body = JSON.stringify(body);
  }

  const response = await fetch(url, fetchConfig);

  if (!response.ok) {
    throw new Error(`API请求失败: ${response.status} ${response.statusText}`);
  }

  return response.json();
}

// 流式请求函数
async function streamRequest(
  url: string,
  config: RequestConfig = {},
): Promise<Response> {
  const { method = "POST", headers = {}, body, signal } = config;

  const fetchConfig: RequestInit = {
    method,
    headers: {
      "Content-Type": "application/json",
      ...headers,
    },
    signal,
  };

  if (body) {
    fetchConfig.body = JSON.stringify(body);
  }

  const response = await fetch(url, fetchConfig);

  if (!response.ok) {
    throw new Error(`流式请求失败: ${response.status} ${response.statusText}`);
  }

  return response;
}

// ==================== 聊天相关API ====================

export interface ChatRequest {
  question: string;
  chatId: string;
  overrideConfig?: any;
  streaming?: boolean;
  humanInput?: {
    type: "proceed" | "reject";
    startNodeId: string;
    feedback: string;
  };
}

/**
 * 发送聊天请求
 */
export async function sendChatMessage(
  params: ChatRequest,
  signal?: AbortSignal,
): Promise<Response> {
  const url = `${CHAT_API_CONFIG.BASE_URL}/${CHAT_API_CONFIG.FLOW_ID}`;

  return streamRequest(url, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${CHAT_API_CONFIG.API_KEY}`,
    },
    body: params,
    signal,
  });
}

/**
 * 中止聊天
 */
export async function abortChat(
  chatId: string,
  flowId?: string,
): Promise<void> {
  const actualFlowId = flowId || CHAT_API_CONFIG.FLOW_ID;
  const url = `${CHAT_API_CONFIG.ABORT_URL}/${actualFlowId}/${chatId}`;

  await request(url, {
    method: "PUT",
    headers: {
      Authorization: `Bearer ${CHAT_API_CONFIG.API_KEY}`,
    },
  });
}

// ==================== AI模型相关API ====================

export interface AIGenerateRequest {
  model?: string;
  prompt: string;
  stream?: boolean;
  options?: {
    temperature?: number;
    top_p?: number;
    max_tokens?: number;
  };
}

/**
 * AI内容生成
 */
export async function generateAIContent(
  params: AIGenerateRequest,
): Promise<any> {
  return request(AI_MODEL_CONFIG.BASE_URL, {
    method: "POST",
    body: {
      model: AI_MODEL_CONFIG.MODEL,
      stream: false,
      options: {
        temperature: 0.3,
        top_p: 0.8,
        max_tokens: 3000,
      },
      ...params,
    },
  });
}

// ==================== 内容管理相关API ====================

export interface CreateContentRequest {
  city: string;
  title: string;
  pageDiv: string;
  content: string;
  durationDays: number;
  tags: string[];
}

export interface CreateContentResponse {
  data?: {
    id: string;
  };
  id?: string;
}

export interface ProductResponse {
  data?: {
    pageDiv: string;
    language?: string; // 新增：产品内容的语言编码
    [key: string]: any;
  };
  [key: string]: any;
}

/**
 * 创建内容
 */
export async function createContent(
  params: CreateContentRequest,
): Promise<CreateContentResponse> {
  const url = `${CONTENT_API_CONFIG.BASE_URL}/createContent`;

  return request<CreateContentResponse>(url, {
    method: "POST",
    body: params,
  });
}

/**
 * 根据产品ID获取产品数据
 */
export async function getProductById(
  productId: string,
  lang: string,
): Promise<ProductResponse> {
  const url = `${CONTENT_API_CONFIG.BASE_URL}/${productId}?lang=${lang}`;

  return request<ProductResponse>(url, {
    method: "GET",
  });
}

// ==================== 思维链相关API ====================

export interface ThinkingChainRequest {
  question: string;
  overrideConfig?: any;
  chatId: string;
  streaming?: boolean;
}

/**
 * 发送思维链请求
 */
export async function sendThinkingChainRequest(
  params: ThinkingChainRequest,
  callbacks?: {
    onSuccess?: (messages: any) => void;
    onError?: (error: any) => void;
    onUpdate?: (msg: any) => void;
  },
): Promise<void> {
  const url = `${THINKING_CHAIN_CONFIG.BASE_URL}/${params.chatId}`;

  // 这里可以根据实际需要实现流式处理逻辑
  // 目前先保持原有的XRequest逻辑
  throw new Error("思维链请求需要使用XRequest实现，请直接使用XRequest");
}

// ==================== 总结相关API ====================

export interface SummaryRequest {
  content: string[]; // 支持字符串或字符串数组
  contentType: "product" | "html"; // 内容类型
  chatId: string;
}

/**
 * 解析内容为每日数组
 */
function parseContentToDailyArray(
  content: string[],
  contentType: "product" | "html",
): string[] {
  const dailyArray: string[] = [];

  if (contentType === "product") {
    // 对于产品类型：优先按 <table class="print_table"> 标签分段
    const tableRegex =
      /<table[^>]*class="print_table"[^>]*>([\s\S]*?)<\/table>/g;
    let match;
    let hasTable = false;

    // 将数组内容合并为单个字符串进行处理
    const contentString = content.join("\n");

    while ((match = tableRegex.exec(contentString)) !== null) {
      hasTable = true;
      const tableHtml = match[0]; // 完整的table标签

      // 将HTML表格转换为Markdown格式
      const markdown = convertTableHtmlToMarkdown(tableHtml);

      if (markdown.trim()) {
        dailyArray.push(markdown.trim());
      }
    }

    // 如果没有找到table标签，则将HTML转换为Markdown后按一级标题分段
    if (!hasTable) {
      const markdown = convertHtmlToMarkdown(contentString);
      return parseMarkdownByHeaders(markdown);
    }
  } else if (contentType === "html") {
    // 对于HTML类型：将数组合并后按Markdown的一级标题(#)分段
    const contentString = content.join("\n");
    return parseMarkdownByHeaders(contentString);
  }

  return dailyArray;
}

/**
 * 将HTML转换为Markdown
 */
function convertHtmlToMarkdown(html: string): string {
  // 使用turndown将HTML转换为Markdown
  const markdown = turndownService.turndown(html);

  // 清理转换结果
  const cleanedMarkdown = markdown
    .replace(/\n{3,}/g, "\n\n") // 将多个连续换行替换为最多2个
    .replace(/^\s+|\s+$/g, "") // 去除首尾空白
    .trim();

  if (!cleanedMarkdown) {
    throw new Error("HTML转Markdown失败: 无法解析HTML内容");
  }

  return cleanedMarkdown;
}

/**
 * 按Markdown一级标题分段
 */
function parseMarkdownByHeaders(content: string): string[] {
  const dailyArray: string[] = [];
  const lines = content.split("\n");
  let currentDayContent = "";

  for (const line of lines) {
    if (line.trim().startsWith("#") && !line.trim().startsWith("##")) {
      // 遇到一级标题，保存前一天的内容
      if (currentDayContent.trim()) {
        dailyArray.push(currentDayContent.trim());
      }
      // 开始新的一天
      currentDayContent = line + "\n";
    } else {
      currentDayContent += line + "\n";
    }
  }

  // 添加最后一天的内容
  if (currentDayContent.trim()) {
    dailyArray.push(currentDayContent.trim());
  }

  return dailyArray;
}

/**
 * 将HTML表格转换为Markdown格式
 */
function convertTableHtmlToMarkdown(tableHtml: string): string {
  let markdown = "";

  // 提取表格标题（如果有的话）
  const titleMatch = tableHtml.match(
    /<div[^>]*class="print_table_title"[^>]*>(.*?)<\/div>/,
  );
  if (titleMatch) {
    // 使用turndown处理标题HTML
    const titleHtml = titleMatch[1];
    const titleMarkdown = turndownService.turndown(titleHtml);
    if (titleMarkdown.trim()) {
      markdown += `## ${titleMarkdown.trim()}\n\n`;
    }
  }

  // 提取所有行内容
  const rowRegex = /<tr[^>]*>([\s\S]*?)<\/tr>/g;
  let rowMatch;
  const rows = [];

  while ((rowMatch = rowRegex.exec(tableHtml)) !== null) {
    const rowContent = rowMatch[1];

    // 提取单元格内容
    const cellRegex = /<t[hd][^>]*>([\s\S]*?)<\/t[hd]>/g;
    let cellMatch;
    const cells = [];

    while ((cellMatch = cellRegex.exec(rowContent)) !== null) {
      const cellHtml = cellMatch[1];

      // 使用turndown处理单元格HTML内容
      const cellMarkdown = turndownService.turndown(cellHtml);

      if (cellMarkdown.trim()) {
        cells.push(cellMarkdown.trim());
      }
    }

    if (cells.length > 0) {
      rows.push(cells);
    }
  }

  // 将行数据转换为Markdown格式
  if (rows.length > 0) {
    // 检查是否有表头
    const hasHeader = tableHtml.includes("<th");

    if (hasHeader && rows.length > 0) {
      // 第一行作为表头
      const headerRow = rows[0];
      markdown += "| " + headerRow.join(" | ") + " |\n";
      // 注意：不添加分隔符行，避免产生多余的"---"元素

      // 其余行作为数据行
      for (let i = 1; i < rows.length; i++) {
        markdown += "| " + rows[i].join(" | ") + " |\n";
      }
    } else {
      // 没有表头，所有行都是数据行，使用列表格式
      rows.forEach((row) => {
        markdown += "- " + row.join(" ") + "\n";
      });
    }
  }

  // 提取表格外的其他内容
  const otherContentRegex =
    /<div[^>]*class="print_table_td_text"[^>]*>([\s\S]*?)<\/div>/g;
  let otherMatch;

  while ((otherMatch = otherContentRegex.exec(tableHtml)) !== null) {
    const otherHtml = otherMatch[1];

    // 使用turndown处理其他HTML内容
    const otherMarkdown = turndownService.turndown(otherHtml);

    if (otherMarkdown.trim()) {
      markdown += "\n" + otherMarkdown.trim() + "\n";
    }
  }

  if (!markdown.trim()) {
    throw new Error("表格转换失败: 无法提取有效的表格内容");
  }

  return markdown;
}

/**
 * 发送总结请求
 */
export async function sendSummaryRequest(
  params: SummaryRequest,
  signal?: AbortSignal,
): Promise<Response> {
  const url = `${SUMMARY_API_CONFIG.BASE_URL}/${SUMMARY_API_CONFIG.FLOW_ID}`;

  // 统一处理输入内容，确保为数组格式
  let dailyArray: string[];

  const { content, contentType } = params;
  if (contentType === "product") {
    dailyArray = parseContentToDailyArray(content, "product");
  } else {
    dailyArray = parseContentToDailyArray(content, "html");
  }

  // 将数组安全地转换为字符串格式，避免特殊字符影响JSON解析
  const dailyArrayString = JSON.stringify(dailyArray, null, 2);

  // 将每日数组字符串作为question参数传递
  const requestBody = {
    question: dailyArrayString, // 传递每日内容数组的字符串表示
    chatId: params.chatId,
    streaming: true,
  };

  return streamRequest(url, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${SUMMARY_API_CONFIG.API_KEY}`,
    },
    body: requestBody,
    signal,
  });
}

/**
 * 提取总结内容
 */
export function extractSummaryContent(text: string): string | null {
  const regex = /<flow_summary_result>([\s\S]*?)<\/flow_summary_result>/;
  const match = text.match(regex);
  return match ? match[1].trim() : null;
}

// ==================== 航班搜索相关 ====================

// 航班搜索请求参数类型
export interface FlightSearchRequest {
  departure: string;
  destination: string;
  tripType: string;
  departDate: string;
  returnDate: string;
  directFlight: boolean;
  adults: number;
  children: number;
  infants: number;
}

export interface FlightSearchResponse {
  code: number;
  success: boolean;
  message: string;
  data: {
    success: boolean;
    message: string | null;
    transactionId: string;
    timestamp: string;
    searchRequest: FlightSearchRequest;
    flights: FlightOption[];
  };
}

export interface FlightOption {
  itineraryId: string;
  priceIndex: number;
  transferCount: number;
  crossDays: number;
  outboundFlight: {
    flightNumber_lang: string;
    baggageInfo_lang: string;
    duration_lang: string;
    airline_lang: string;
    arrivalCity_lang: string;
    departureCity_lang: string;
    baggageInfo: any;
    flightNumber: string;
    airline: string;
    departureTime: string;
    arrivalTime: string;
    duration: string;
    departureAirport: string;
    arrivalAirport: string;
    departureCity: string;
    arrivalCity: string;
    currency: string;
  };
  returnFlight: {
    flightNumber_lang: string;
    duration_lang: string;
    airline_lang: string;
    arrivalCity_lang: string;
    departureCity_lang: string;
    flightNumber: string;
    airline: string;
    departureTime: string;
    arrivalTime: string;
    duration: string;
    departureAirport: string;
    arrivalAirport: string;
    departureCity: string;
    arrivalCity: string;
    currency: string;
  };
  adultTotalPrice: number;
  childTotalPrice: number;
  infantTotalPrice: number;
  currency: string;
  totalDuration: string;
  ticketCount: number;
}

/**
 * 搜索航班
 */
export async function searchFlights(
  params: FlightSearchRequest,
): Promise<FlightSearchResponse> {
  const url = FLIGHT_SEARCH_CONFIG.BASE_URL;

  const response = await request<FlightSearchResponse>(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: params,
  });
  const lang = i18n.language
  if (lang === 'zh') return response

  const arrivalCity = await translateText(params.destination, 'zh', lang)
  const departureCity = await translateText(params.departure, 'zh', lang)
  const airlines: { [x: string]: string; } = {};
  const baggageInfo: { [x: string]: string; } = {}
  for (const flight of response.data.flights) {
    if (!airlines[flight.outboundFlight.airline]) {
      airlines[flight.outboundFlight.airline] = await translateText(flight.outboundFlight.airline, 'zh', lang)
    }
    if (!airlines[flight.returnFlight.airline]) {
      airlines[flight.returnFlight.airline] = await translateText(flight.returnFlight.airline, 'zh', lang)
    }
    if (!baggageInfo[flight.outboundFlight.baggageInfo]) {
      baggageInfo[flight.outboundFlight.baggageInfo] = await translateText(flight.outboundFlight.baggageInfo, 'zh', lang)
    }
  }
  const handleDuration = (duration: string) => {
    return duration.replace('天', t('chatbox.modals.flightSelection.day')).replace('小时', t('chatbox.modals.flightSelection.hour')).replace('分钟', t('chatbox.modals.flightSelection.minute'))
  }
  response.data.flights.forEach((flight) => {
    flight.outboundFlight.arrivalCity_lang = arrivalCity
    flight.outboundFlight.departureCity_lang = departureCity
    flight.returnFlight.arrivalCity_lang = departureCity
    flight.returnFlight.departureCity_lang = arrivalCity
    flight.outboundFlight.airline_lang = airlines[flight.outboundFlight.airline]
    flight.returnFlight.airline_lang = airlines[flight.returnFlight.airline]
    flight.outboundFlight.duration_lang = handleDuration(flight.outboundFlight.duration)
    flight.returnFlight.duration_lang = handleDuration(flight.returnFlight.duration)
    flight.outboundFlight.baggageInfo_lang = baggageInfo[flight.outboundFlight.baggageInfo]
    flight.outboundFlight.flightNumber_lang = airlines[flight.outboundFlight.airline] + " " + flight.outboundFlight.flightNumber.split(' ')[1]
    flight.returnFlight.flightNumber_lang = airlines[flight.returnFlight.airline] + " " + flight.returnFlight.flightNumber.split(' ')[1]
  });

  return response;
}

// ==================== 时间处理相关 ====================

/**
 * 时间处理API返回的数据结构
 */
export interface TimeDataResult {
  first?: string[];
  lastDay?: string[];
  firstTitle?: string;
  lastDayTitle?: string;
  reason?: string;
}

/**
 * 简化的航班时间信息
 */
export interface SimplifiedFlightInfo {
  outboundDepartureTime?: string;
  outboundArrivalTime?: string;
  returnDepartureTime?: string;
  returnArrivalTime?: string;
}

/**
 * 处理时间数据 - 调用指定的 flowID 来处理航班时间信息和页面内容
 * 返回需要移除的时间信息结构
 */
export async function processTimeData(
  flightTimeInfo: SimplifiedFlightInfo,
  firstDayContent: string,
  lastDayContent: string,
  firstTitle: string,
  lastDayTitle: string,
  chatId: string,
): Promise<TimeDataResult> {
  const url = `${TIME_PROCESSING_CONFIG.BASE_URL}/${TIME_PROCESSING_CONFIG.FLOW_ID}`;

  const requestData = {
    question: JSON.stringify({
      flightTimeInfo,
      firstDayContent,
      lastDayContent,
      firstTitle,
      lastDayTitle,
    }),
    chatId: chatId,
    streaming: false,
  };

  try {
    const response = await request(url, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${TIME_PROCESSING_CONFIG.API_KEY}`,
        "Content-Type": "application/json",
      },
      body: requestData,
    });

    // flowID 返回的结果中有一个 text 字段，这是 JSON 字符串，需要解析
    let result = response.data || response;

    if (result.text) {
      try {
        // 解析 text 字段中的 JSON 字符串
        const parsedText = JSON.parse(result.text);
        return parsedText;
      } catch (parseError) {
        console.error(
          "解析 text 字段失败:",
          parseError,
          "原始 text:",
          result.text,
        );
        // 如果解析失败，尝试直接返回 result
        return result;
      }
    }

    // 如果没有 text 字段，直接返回结果
    // 期望返回 { "first": ["13:00", "下午"], "lastDay": ["19:00"] } 这样的结构
    return result;
  } catch (error) {
    console.error("Error processing time data:", error);
    throw error;
  }
}

// ==================== 错误处理 ====================

export class ApiError extends Error {
  constructor(
    public status: number,
    public statusText: string,
    message?: string,
  ) {
    super(message || `API Error: ${status} ${statusText}`);
    this.name = "ApiError";
  }
}

// ==================== 工具函数 ====================

/**
 * 创建带取消功能的请求
 */
export function createCancellableRequest() {
  const abortController = new AbortController();

  return {
    signal: abortController.signal,
    cancel: () => abortController.abort(),
  };
}

/**
 * 处理流式响应
 */
export async function* processStreamResponse(response: Response) {
  const reader = response.body?.getReader();
  if (!reader) {
    throw new Error("No readable stream");
  }

  const decoder = new TextDecoder();

  try {
    while (true) {
      const { done, value } = await reader.read();

      if (done) break;

      const chunk = decoder.decode(value, { stream: true });
      yield chunk;
    }
  } finally {
    reader.releaseLock();
  }
}

// 翻译请求类型
export interface TranslateRequest {
  q: string;           // 待翻译文本
  from_lang: string;   // 源语言
  to_lang: string;     // 目标语言
}

// 翻译响应类型
export interface TranslateResponse {
  from_lang: string;
  to_lang: string;
  trans_result: Array<{
    src: string;
    dst: string;
  }>;
}

// 多语言产品保存请求类型
export interface SaveProductMultilangRequest {
  productId: string;
  languageCode: string;
  pageContentMarkdown: string;
  translatedContent: string;
}

// 多语言产品保存响应类型
export interface SaveProductMultilangResponse {
  code: number;
  success: boolean;
  message: string;
  data: null;
}

/**
 * 翻译文本
 * @param text 待翻译文本
 * @param fromLang 源语言
 * @param toLang 目标语言
 * @param signal 取消信号
 * @returns 翻译结果
 */
export async function translateText(
  text: string,
  fromLang: string = "zh",
  toLang: string = "en",
  signal?: AbortSignal,
): Promise<string> {
  try {
    const request: TranslateRequest = {
      q: text,
      from_lang: fromLang,
      to_lang: toLang,
    };

    const response = await fetch(TRANSLATE_API_CONFIG.BASE_URL, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Accept": "application/json",
      },
      body: JSON.stringify(request),
      signal,
    });

    if (!response.ok) {
      throw new Error(`翻译请求失败: ${response.status} ${response.statusText}`);
    }

    const result: TranslateResponse = await response.json();

    if (result.trans_result && result.trans_result.length > 0) {
      // 将所有翻译结果用换行符拼接起来
      const res = result.trans_result.map(item => item.dst).join('\n');
      return res.replaceAll(" **", "**").replaceAll("** ", "**");
    } else {
      throw new Error('翻译结果为空');
    }
  } catch (error) {
    console.error("翻译API调用失败:", error);
    // 如果翻译失败，返回原文
    return text;
  }
}

/**
 * 保存多语言产品内容
 * @param params 保存参数
 * @param signal 取消信号
 */
export async function saveProductMultilang(
  params: SaveProductMultilangRequest,
  signal?: AbortSignal,
): Promise<SaveProductMultilangResponse> {
  const url = CONTENT_API_BASE_URL + "/apis/ctrip/multilang/saveProductMultilang";
  let { productId, languageCode, pageContentMarkdown, translatedContent } = params
  translatedContent = translatedContent.replaceAll('---', '<hr/>').replace(/!\[([^\]]*)\]\(([^)]+)\)/g, (match, alt, src) => {
    return `<p><img src="${src}" alt="${alt}" style="max-height:300px;" /></p>`;
  }).split(/\n{2,}/)           // 两个换行以上当成新段落
    .map(p => `<p>${p.trim()}</p>`)
    .join('');
  try {
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Accept": "application/json",
      },
      body: JSON.stringify({
        productId,
        languageCode,
        pageContentMarkdown,
        translatedContent
      }),
      signal,
    });

    if (!response.ok) {
      throw new Error(`保存多语言产品内容失败: ${response.status} ${response.statusText}`);
    }

    const result: SaveProductMultilangResponse = await response.json();
    return result;
  } catch (error) {
    console.error("保存多语言产品内容API调用失败:", error);
    throw error;
  }
}

export default {
  // 聊天相关
  sendChatMessage,
  abortChat,

  // AI生成相关
  generateAIContent,

  // 内容管理相关
  createContent,
  getProductById,

  // 总结相关
  sendSummaryRequest,
  extractSummaryContent,

  // 工具函数
  createCancellableRequest,
  processStreamResponse,

  // 航班搜索相关
  searchFlights,

  // 时间处理相关
  processTimeData,

  // 翻译相关
  translateText,
};
